﻿using System;
using System.Collections.Generic;
using System.Threading;
using Noria.Web.MyMSDN.Tasks;
using Noria.Web.Utility;

// Load the configuration from the 'WebApp.dll.log4net' file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace Noria.Web.MyMSDN
{
    public class Global : System.Web.HttpApplication
    {
        // Create a logger for use in this class
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private readonly ErrorHandler handler = new ErrorHandler();
        private readonly NTask spider = new SpiderTask();
        private readonly NTask heart = new HeartBeatTask();

        protected void Application_Start(object sender, EventArgs e)
        {
            log.Info("Application_Start");

            Doctor.PrintSystemInfo();

            spider.Start();
            heart.Start();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            // set response stream encoding
            var encoding = Doctor.AnalyzeEncoding(Context);

            log.InfoFormat("Application_BeginRequest -> [{0}][{1}][{2}]{3}",
                ClientHelper.GetIPAddress(Context.Request), 
                Context.Request.HttpMethod, encoding, Context.Request.Url);
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            handler.Process(Context.Response, Context.Server.GetLastError());
            Context.Server.ClearError();
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
            heart.Stop();
            spider.Stop();
            log.Info("Application_End");
        }
    }
}